<?php
require_once("../../../../mysql.connect.php");
session_start();

if(!isset($_POST['text'])){
	$start = 0; 
	if(is_numeric($_GET['start'])){
		$start = $_GET['start'];
	}
	if($start == 0){
		$data = mysql_query("SELECT plugin_userchat.id,username,text FROM plugin_userchat LEFT JOIN (users) ON (users.id=plugin_userchat.userid) WHERE plugin_userchat.id > ((SELECT MAX(plugin_userchat.id) FROM plugin_userchat) - 20)");
	}else {
		$data = mysql_query("SELECT plugin_userchat.id,username,text FROM plugin_userchat LEFT JOIN (users) ON (users.id=plugin_userchat.userid) LIMIT $start, 20");
	}
	// install plugin if no database found.
	if(mysql_errno() == 1146){
		require_once("plugin.php");
		require_once("exec.php");
		$PluginUserChat->Install();
	}
	
	$ar = array();

	while($row = mysql_fetch_array($data, MYSQL_ASSOC)){
		$ar[] = array("id" => $row['id'], "username" => $row['username'], "text" => $row['text']);
	}
	echo json_encode($ar);
}else {
	if(isset($_SESSION['user']) == false){
		echo json_encode(array("stats" => "login"));
	}else if(strlen($_POST['text']) <= $_SESSION['sys']['core_shoutbox_maxlen'] && strlen($_POST['text']) >= $_SESSION['sys']['core_shoutbox_minlen']){
		mysql_query("INSERT INTO plugin_userchat (userid, text) VALUES ({$_SESSION['user']['id']}, \"".htmlentities(str_replace("\n", "", $_POST['text']),ENT_COMPAT,'utf-8')."\")");
		echo json_encode(array("stats" => "good", "ret" => $_POST['text']));
	}else if(strlen($_POST['text']) > $_SESSION['sys']['core_shoutbox_maxlen']){
		echo json_encode(array("stats" => "toolong", "max" => $_SESSION['sys']['core_shoutbox_maxlen']));
	}else if(strlen($_POST['text']) < 3){
		echo json_encode(array("stats" => "tooshort", "min" => $_SESSION['sys']['core_shoutbox_minlen']));
	}
}